package com.wys.spring.mqtt;


import com.wys.utils.JsonUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;

@Configuration
@EnableConfigurationProperties(EMQXProperties.class)
@ConditionalOnProperty(name = "emqx.enable", havingValue = "true")
public class EMQXAutoConfig {

    private static final Logger log = LoggerFactory.getLogger(EMQXAutoConfig.class);

    @Bean
    @ConditionalOnMissingBean
    public MqttClient mqttClient(EMQXProperties emqxProperties) throws MqttException {
        MqttClient mqttClient = new MqttClient(emqxProperties.getHost()[0], emqxProperties.getClientId());
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(emqxProperties.getUserName());
        mqttConnectOptions.setPassword(emqxProperties.getPassword().toCharArray());
        mqttConnectOptions.setConnectionTimeout(emqxProperties.getConnectionTimeout());
        mqttConnectOptions.setKeepAliveInterval(emqxProperties.getKeepAliveInterval());
        if (ObjectUtils.isNotEmpty(emqxProperties.getWill()) && StringUtils.isNotBlank(emqxProperties.getWill().getTopic())) {
            mqttConnectOptions.setWill(emqxProperties.getWill().getTopic(), emqxProperties.getWill().getPayload().getBytes(StandardCharsets.UTF_8),
                    emqxProperties.getWill().getQos(), emqxProperties.getWill().getRetained());
        }
        log.info("------------开始尝试连接mqtt服务器ip地址:{}", JsonUtils.object2Json(emqxProperties.getHost()));
        mqttClient.connect(mqttConnectOptions);
        return mqttClient;
    }


}
